import { useSiteConfig } from '../store/siteConfig'
import axios from 'axios'
import { ElLoading, ElNotification } from 'element-plus'
import { useAdminInfo } from '../store/adminInfo'
import { i18n } from '../lang/index'
import router from '../router/index'

const adminInfo = useAdminInfo()
const siteConfig = useSiteConfig()
const apiUrl = siteConfig.apiUrl

const loadingInstance = {
    target: null,
    count: 0,
}

/**
 * 关闭Loading层实例
 */
function closeLoading(options) {
    if (options.loading) {
        if (loadingInstance.count > 0) loadingInstance.count--
        if (loadingInstance.count === 0) {
            if(loadingInstance.target){
                loadingInstance.target.close()
            }
            loadingInstance.target = null
        }
    }
}

function createAxios (axiosConfig,options,loading){
    const Axios = axios.create({
        baseURL: apiUrl,
        timeout: 1000 * 10,
        responseType: 'json',
    })
    options = Object.assign(
        {
            loading: false, // 是否开启loading层效果, 默认为false
            showErrorMessage: true, // 是否开启接口错误信息展示,默认为true
            showCodeMessage: false, // 是否开启code不为1时的信息提示, 默认为true
            showSuccessMessage: false, // 是否开启code为1时的信息提示, 默认为false
        },
        options
    )
    if (options.loading) {
        loadingInstance.count++
        if (loadingInstance.count === 1) {
            loadingInstance.target = ElLoading.service(loading)
        }
    }
    // 请求拦截
    Axios.interceptors.request.use(
        (config) => {
            // 创建loading实例
            if (options.loading) {
                loadingInstance.count++
                if (loadingInstance.count === 1) {
                    loadingInstance.target = ElLoading.service(loading)
                }
            }

            // 自动携带token
            if (config.headers) {
                const token = adminInfo.getToken()
                if (token) (config.headers).Authorization = 'Bearer ' + token
            }

            return config
        },
        (error) => {
            return error
        }
    )
    // 响应拦截
    Axios.interceptors.response.use(
        (response) => {
            options.loading && closeLoading(options) // 关闭loading
            if (response.config.responseType == 'json') {
                if (response.data && response.data.code !== 200) {
                    console.log(response.data)
                    if (response.data.code == 409) {
                        //这里需要刷新token逻辑暂时加长token有效期无需刷新
                        router.push({ name: 'login' })
                    }
                    if(response.data.code == 401){
                        router.push({ name: 'login' })
                    }
                    if (options.showErrorMessage===true) {
                        if (response.data.msg) {
                            ElNotification({
                                type: 'error',
                                message: response.data.msg,
                            })
                        }else{
                            ElNotification({
                                type: 'error',
                                message: i18n.global.t('axios.Abnormal problem, please contact the website administrator!'),
                            })
                        }
                    }
                } else if (options.showSuccessMessage && response.data && response.data.code == 1) {
                    ElNotification({
                        message: response.data.msg ? response.data.msg : i18n.global.t('axios.Operation successful'),
                        type: 'success',
                    })
                }
            }
            closeLoading(options) // 关闭loading
            return options.reductDataFormat ? response.data : response
        },
        (error) => { 
            closeLoading(options) // 关闭loading
            options.showErrorMessage && httpErrorStatusHandle(error) // 处理错误状态码
            return error //Promise.reject(error) // 错误继续返回给到具体页面
        }
    )
    return Axios(axiosConfig)
}

export async function callBackWebapi(method,data,options,loading){
    var response =  new createAxios(
        {
            url: method,
            data: data,
            method: 'post'
        }
        ,options,loading
    ).then((res) => {
        return res.data
    }).finally((error) => {
        closeLoading(options)
        return error
    })
    // ;(async () => {
    //     const result = await response;
    //     console.log(result); // 这里会打印获取到的数据或者错误信息
    //     return result
    // })();
    return await response
}

/**
 * 处理异常
 * @param {*} error
 */
function httpErrorStatusHandle(error) {
    // 处理被取消的请求
    if (axios.isCancel(error)) return console.error(i18n.global.t('axios.Automatic cancellation due to duplicate request:') + error.message)
    let message = ''
    if (error && error.response) {
        switch (error.response.status) {
            case 302:
                message = i18n.global.t('axios.Interface redirected!')
                break
            case 400:
                message = i18n.global.t('axios.Incorrect parameter!')
                break
            case 401:
                message = i18n.global.t('axios.You do not have permission to operate!')
                break
            case 403:
                message = i18n.global.t('axios.You do not have permission to operate!')
                break
            case 404:
                message = i18n.global.t('axios.Error requesting address:') + error.response.config.url
                break
            case 408:
                message = i18n.global.t('axios.Request timed out!')
                break
            case 409:
                message = i18n.global.t('axios.The same data already exists in the system!')
                break
            case 500:
                message = i18n.global.t('axios.Server internal error!')
                break
            case 501:
                message = i18n.global.t('axios.Service not implemented!')
                break
            case 502:
                message = i18n.global.t('axios.Gateway error!')
                break
            case 503:
                message = i18n.global.t('axios.Service unavailable!')
                break
            case 504:
                message = i18n.global.t('axios.The service is temporarily unavailable Please try again later!')
                break
            case 505:
                message = i18n.global.t('axios.HTTP version is not supported!')
                break
            default:
                message = i18n.global.t('axios.Abnormal problem, please contact the website administrator!')
                break
        }
    }
    if (error.message.includes('timeout')) message = i18n.global.t('axios.Network request timeout!')
    if (error.message.includes('Network'))
        message = window.navigator.onLine ? i18n.global.t('axios.Server exception!') : i18n.global.t('axios.You are disconnected!')

    ElNotification({
        type: 'error',
        message,
    })
}